package com.ohuang.test_compose.composeView

import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.lifecycle.MutableLiveData
import java.util.Stack

/**
 * PageRouter与ComposePager配合时候
 * 实现compose界面跳转
 */
class PageRouter {

    private var stack = Stack<PageRouterObj>()

    var state = MutableLiveData<PageRouterObj?>()

    fun remove(): Boolean {
        return if (stack.empty()) {
            false
        } else {
            stack.pop()
            if (stack.isEmpty()) {
                state.value = null
            } else {
                state.value = stack.peek()
            }
            true
        }
    }

    fun add(content: (@Composable () -> Unit)) {
        stack.push(PageRouterObj(content))
        state.value = stack.peek()
    }

    fun replace(content: (@Composable () -> Unit)) {
        if (!stack.isEmpty()) {
            stack.pop()
        }
        add(content)
    }

    /**
     * 判断是否还有page
     */
    fun isEmpty(): Boolean {
        return stack.isEmpty()
    }

}


class PageRouterObj(val content: (@Composable () -> Unit)) {
}

@Composable
fun ComposePager(pageRouter: PageRouter, content: (@Composable() () -> Unit) = {}) {
    val state by pageRouter.state.observeAsState()
    if (state != null) {
        state!!.content()
    } else {
        content()
    }
}

